package com.lanyam.travel.base.controller;

import java.text.ParseException;
import java.util.*;

import javax.annotation.security.RolesAllowed;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.core.type.TypeReference;
import com.lanyam.travel.base.entity.vo.DistrUserVo;
import com.lanyam.travel.base.utils.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lanyam.travel.base.entity.Permission;
import com.lanyam.travel.base.entity.Role;
import com.lanyam.travel.base.entity.ScenicHotel;
import com.lanyam.travel.base.entity.TravelLine;
import com.lanyam.travel.base.entity.TravelMenu;
import com.lanyam.travel.base.entity.User;
import com.lanyam.travel.base.entity.vo.FormReport;
import com.lanyam.travel.base.entity.vo.TravelOrderVo;
import com.lanyam.travel.base.entity.vo.UserVo;
import com.lanyam.travel.base.service.UserService;

import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("user")
@Api(tags="用户API")
public class UserController {

	@Autowired
	private UserService userService;
	
	/**
	 * 添加管理员
	 * @param phone
	 * @param password
	 * @param name
	 * @return
	 * @throws Exception
	 */
	@RequiresRoles(value={"superAdmin"})
	@PostMapping("/addAdminUser")
	public JSONResult addAdminUser(@RequestBody User user) throws Exception
	{
		if(StringUtils.isEmpty(user.getPhone()) || StringUtils.isEmpty(user.getPassword()))
		{
			return JSONResult.errorMsg("手机号密码不能为空!");
		}
		// 2. 判断手机号是否存在
		String phone = user.getPhone();
		User existUser = userService.queryPhoneIsExist(phone);
		
		// 3. 保存用户，注册信息
		if (null == existUser) {
			String id = UUID.randomUUID().toString().replace("-", "");
			user.setId(id);
			user.setPassword(MD5Utils.getMD5Str(user.getPassword()));
			user.setStatus(1);
			user.setCreateDate(new Date());
			user.setUpdateDate(new Date());
			userService.saveUser(user);
			user.setPassword("");
			return JSONResult.ok(user);
		} else {
			return JSONResult.errorMsg("该手机号已注册，请更换手机号");
		}
	}
	
	/**
	 * 增加普通会员
	 * @param user
	 * @return
	 * @throws Exception 
	 */
	@PostMapping("/addNormalUser")
	public JSONResult addNormalUser(@RequestBody User user) throws Exception
	{
		if(StringUtils.isEmpty(user.getPhone()) || StringUtils.isEmpty(user.getPassword()))
		{
			return JSONResult.errorMsg("手机号密码不能为空!");
		}
		// 2. 判断手机号是否存在
		String phone = user.getPhone();
		User existUser = userService.queryPhoneIsExist(phone);
		
		// 3. 保存用户，注册信息
		if (null == existUser) {
			String id = UUID.randomUUID().toString().replace("-", "");
			user.setId(id);
			user.setPassword(MD5Utils.getMD5Str(user.getPassword()));
			user.setStatus(1);
			user.setCreateDate(new Date());
			user.setUpdateDate(new Date());
			userService.saveUser(user);
			user.setPassword("");
			return JSONResult.ok(user);
		} else {
			return JSONResult.errorMsg("该手机号已注册，请更换手机号");
		}
	}
	/**
	 * 上传用户的身份证/护照
	 * @param userId
	 * @param fileType 0：身份证正面，1：身份证反面，2：护照正面，3：护照反面
	 * @param file
	 * @return
	 */
	@PostMapping("/uploadUserFile")
	public JSONResult uploadUserFile(String userId,int fileType,@RequestParam(value = "file", required = false) MultipartFile file)
	{
		if(StringUtils.isEmpty(userId) || StringUtils.isEmpty(fileType+"")|| null == file)
		{
			return JSONResult.errorMsg("参数不全。");
		}
		User user = userService.queryUserById(userId);
		String baseUri = Constant.FILE_UPLOAD_BASE_URI;
		if(fileType == 0)
		{
			String dbPathUri = "/img/user/"+userId+"/idfrond";
			FileUtil.delAllFile(baseUri+dbPathUri);
			String imgUri = FileUtil.uploadFile(file, dbPathUri);
			user.setIdCardFrontImg(imgUri);
		}
		else if(fileType == 1)
		{
			String dbPathUri = "/img/user/"+userId+"/idback";
			FileUtil.delAllFile(baseUri+dbPathUri);
			String imgUri = FileUtil.uploadFile(file, dbPathUri);
			user.setIdCardBackImg(imgUri);
		}
		else if(fileType == 2)
		{
			String dbPathUri = "/img/user/"+userId+"/portfront";
			FileUtil.delAllFile(baseUri+dbPathUri);
			String imgUri = FileUtil.uploadFile(file, dbPathUri);
			user.setPassportCardFrontImg(imgUri);
		}
		else 
		{
			String dbPathUri = "/img/user/"+userId+"/portback";
			FileUtil.delAllFile(baseUri+dbPathUri);
			String imgUri = FileUtil.uploadFile(file, dbPathUri);
			user.setPassportCardBackImg(imgUri);
		}
		userService.updateUser(user);
		return JSONResult.ok(user);
	}
	
	/**
	 * 获取管理员列表
	 * @param page
	 * @param pageSize
	 * @param reqPara
	 * @return
	 */
	@RequiresRoles(value={"admin", "superAdmin"},logical= Logical.OR)
	@PostMapping("/queryAdminPage")
	public JSONResult queryAdminPage(int page,int pageSize,@RequestBody(required = false) Map<String,String> reqPara)
	{
		Page<UserVo> ipage = userService.queryAdminPage(page,pageSize,reqPara);
		return JSONResult.ok(ipage.getRecords());
	}
	
	/**
	 * 获取普通会员分页数据
	 * @param page
	 * @param pageSize
	 * @param reqPara id:会员id,name:会员名称,phone:会员手机号,idCard:会员身份证号码,passportCard:会员护照号码
	 * @return
	 */
	@PostMapping("/queryUsersByPage")
	@ApiOperation(value="获取用户分页数据")
	public JSONResult queryUsersByPage(int page,int pageSize,@RequestBody(required = false) Map<String,String> reqPara)
	{
		
		List<User> records = userService.queryUsersByPage(page,pageSize,reqPara);
		return JSONResult.ok(records);
	}

	/**
	 * 获取用户分页数据
	 * @param page
	 * @param pageSize
	 * @param reqPara
	 * @return
	 */
	@PostMapping("/getUsersByPage")
	@ApiOperation(value="获取用户分页数据")
	public JSONResult getUsersByPage(int page,int pageSize,@RequestBody(required = false) Map<String,String> reqPara)
	{

		Page<User> usersByPage = userService.getUsersByPage(page, pageSize, reqPara);
		return JSONResult.ok(usersByPage);
	}
	
	/**
	 * 根据id获取用户信息
	 * @param id
	 * @return
	 */
	@PostMapping("/getUserById")
	public JSONResult getUserById(String id)
	{
		if(StringUtils.isEmpty(id))
		{
			return JSONResult.errorMsg("参数不全");
		}
		UserVo userVo = userService.getUserById(id);
		userVo.setPassword("");
		return JSONResult.ok(userVo);
	}
	/**
	 * 更新用户信息
	 * @param user
	 * @return
	 */
	@PostMapping("/updateUser")
	public JSONResult updateUser(@RequestBody User user)
	{
		user.setUpdateDate(new Date());
		userService.updateUser(user);
		return JSONResult.ok();
	}
	
	/**
	 * 更新用户的角色
	 * @param userId
	 * @param roleId
	 * @return
	 */
	@PostMapping("/saveUserRole")
	public JSONResult saveUserRole(String userId,String roleId)
	{
		if(StringUtils.isEmpty(userId)|| StringUtils.isEmpty(roleId))
		{
			return JSONResult.errorMsg("参数不全");
		}
		userService.updateUserRole(userId,roleId);
		return JSONResult.ok();
	}
	
	
	/**
	 * 获取所有角色
	 * @return
	 */
	@GetMapping("/getAllRoles")
	public JSONResult getAllRoles()
	{
		List<Role> allRoles = userService.getAllRoles();
		
		return JSONResult.ok(allRoles);
	}
	/**
	 * 获取所有权限
	 * @return
	 */
	@GetMapping("/getAllPermissions")
	public JSONResult getAllPermissions()
	{
		List<Permission> allPermissions = userService.getAllPermissions();
		
		return JSONResult.ok(allPermissions);
	}
	/**
	 * 删除用户
	 * @param loginId 当前登陆的用户id
	 * @param targetId 目标用户的id
	 * @return
	 */
	@RequiresPermissions("user:delete")
	@PostMapping("deleteUser")
	public JSONResult deleteUser(String loginId,String targetId)
	{
		if(StringUtils.isEmpty(loginId)||StringUtils.isEmpty(targetId))
		{
			return JSONResult.errorMsg("参数不全");
		}
		Role targetRole = userService.getRoleByUserId(targetId);
		Role loginRole = userService.getRoleByUserId(loginId);
		if(null == targetRole || loginRole.getPower() > targetRole.getPower())
		{
			userService.deleteUser(targetId);
			return JSONResult.ok();
		}
		else
		{
			return JSONResult.errorMsg("权限不足，删除失败");
		}
	}
	/**
	 * 修改用户登陆密码
	 * @param userId
	 * @param newPassword
	 * @return
	 */
	@RequiresPermissions("user:update")
	@PostMapping("/modifyPassword")
	public JSONResult modifyPassword(String userId,String newPassword)
	{
		if(StringUtils.isEmpty(userId)||StringUtils.isEmpty(newPassword))
		{
			return JSONResult.errorMsg("参数不全");
		}
		String result = userService.modifyPassword(userId,newPassword);
		if("OK".equals(result))
		{
			return JSONResult.ok();
		}
		else 
		{
			return JSONResult.errorMsg(result);
		}
	}
	/**
	  * 获取指定日期内的每天的会员数量
	  * @param startDate 起始日期
	  * @param endDate 结束日期
	  *  @return 
	 * @throws ParseException 
	  */
	@PostMapping("/getUserCountByDays")
	public JSONResult getUserCountByDays(Date startDate,Date endDate)
	{
		 if(null == startDate || null == endDate)
		 {
			 return JSONResult.errorMsg("参数不全");
		 }
		 Map<String,List<Object>> result = userService.getUserCountByDays(startDate,endDate);
		 return JSONResult.ok(result);
	}
	/**
	 * 重置密码
	 * @param userId
	 * @return
	 * @throws Exception 
	 */
	@PostMapping("/resetPassoword")
	public JSONResult resetPassoword(String userId) throws Exception
	{
		if(StringUtils.isEmpty(userId))
		{
			return JSONResult.errorMsg("参数不全");
		}
		User user = userService.queryUserById(userId);
		String password = MD5Utils.getMD5Str("123456");
		user.setPassword(password);
		userService.updateUser(user);
		return JSONResult.ok();
	}

	/**
	 * 分页查询数据
	 */
	@GetMapping("/getPage")
	public IPage<UserVo> getPage (String queryMap,
									   @RequestParam(name="page", defaultValue = "1") Integer page,
									   @RequestParam(name="rows", defaultValue = "10") Integer rows) {
		Map<String, Object> query = JsonMapper.string2Obj(queryMap,new TypeReference<Map<String, Object>>() {});
		query = query==null?new HashMap<>():query;
		IPage<UserVo> pageInfo = userService.getPage(query, page, rows);
		return pageInfo;
	}
	
	/**
	 * 获取当前登陆用户能够展示的菜单
	 * @return
	 */
	@GetMapping("/getCurrentUserMenu")
	public JSONResult getCurrentUserMenu()
	{
		User user = userService.getCurrentUser();
		String roleId = user.getRoleId();
		List<TravelMenu> menusInUser = new ArrayList<TravelMenu>();
		if(!StringUtils.isEmpty(roleId))
		{
			menusInUser = userService.getMenusInUser(user.getId());
			
		}
		return JSONResult.ok(menusInUser);
	}
}
